<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Stock_model extends MY_Model {

	var $table = 'stock_assignment';
	
	//构造函数
	public function __construct() {
		//调用父类构造函数，必不可少
		parent::__construct();
	}

	/**
	 * 取得所有供货商库存
	 * @param array $config
	 * @param array $like
	 * @return array
	 */
	public function getStockAll($config = array(), $result = array()) {
		$where=array();
		$config['totalCount'] = $this->get_search_num($where, $result);
		if($config['offset'] >= $config['totalCount']) {
			$config['offset'] = 0;
			$config['pageNum'] = 1;
		}
		
		$sql="select e.address,a.description,p.name,s.request_number,s.created_at,s.id as sid from ck_stock_assignment as s,ck_product as p,ck_areas_enabled as e,ck_areas as a where s.product_id=p.id and s.address_id=e.id and e.district_id=a.id ";
			if(!empty($result['address']))
			{
				$sql2="and address='{$result['address']}' ";
			}else {
				$sql2='';
			}
			$sql=$sql . $sql2;
		
		$query=$this->db->query($sql); 
		$config['data']=$query->result_array();
		return $config;
	}
	
	/**
	 * 添加供货商库存
	 * @param array $ddata
	 * @return boolean
	 */
	public function addStock($data)
	{		
		$this->db->trans_start();
		$this->db->insert_batch('stock_assignment', $data);
		foreach ($data as $d)
		{
			$query=$this->db->query("update ck_product set stock=stock-{$d['request_number']} where id={$d['product_id']}");
		}
		$this->db->trans_complete();
		return $this->db->trans_status()?true:false;
		
	}
	
	/*
	 * 取得所有添加的地址
	 */
	public function getAreasAll()
	{
		$sql="select ae.*,a.description from ck_areas_enabled ae left join ck_areas a on ae.district_id=a.id";
		$query=$this->db->query($sql);
		$config['data']=$query->result_array();
		return $config;
	}

}
